package com.sensetime.jv.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sensetime.jv.entity.ReturnWrapper;
import com.sensetime.jv.enums.StatusEnum;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * HTTP响应工具类，用于统一处理JSON格式的响应
 */
public class ResponseUtil {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 向客户端发送JSON格式的错误响应
     * @param response HTTP响应对象
     * @param status 错误状态码
     * @param message 错误消息
     * @throws IOException 输出流异常
     */
    public static void sendJsonError(HttpServletResponse response, StatusEnum status, String message) throws IOException {
        response.setStatus(200);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");

        ReturnWrapper result = ReturnWrapper.error(status).msg(message).code(status.getCode());

        try (PrintWriter writer = response.getWriter()) {
            writer.write(objectMapper.writeValueAsString(result));
            writer.flush();
        }
    }

    /**
     * 发送403权限拒绝响应
     */
    public static void sendForbidden(HttpServletResponse response, String message) throws IOException {
        sendJsonError(response, StatusEnum.FORBIDDEN, message);
    }

    /**
     * 发送401未认证响应
     */
    public static void sendUnauthorized(HttpServletResponse response, String message) throws IOException {
        sendJsonError(response, StatusEnum.UNAUTHORIZED, message);
    }
    
}